package com.pro01.tracker.service;

import com.pro01.tracker.mapper.TorrentMapper;
import com.pro01.tracker.mapper.TorrentPeerMapper;
import com.pro01.tracker.mapper.TrackerReportMapper;
import com.pro01.tracker.mapper.UserMapper;
import com.pro01.tracker.pojo.TorrentPeer;
import com.pro01.tracker.pojo.TrackerReport;
import com.pro01.tracker.utils.PeerEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class TrackerService {

    @Autowired
    private TrackerReportMapper trackerReportMapper;

    @Autowired
    private TorrentPeerMapper torrentPeerMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TorrentMapper torrentMapper;

    /**
     * 根据 passkey 查找用户 ID（可用用户Mapper或你已有工具方法）
     */
    public Long getUserIdByPasskey(String passkey) {
        return userMapper.getUserIdByPasskey(passkey);
    }

    public Long getTorrentIdByInfoHash(String infoHash) {
        return torrentMapper.getTorrentIdByInfoHash(infoHash);
    }

    public List<PeerEncoder.PeerInfo> getPeersForTorrent(Long torrentId) {
        List<TorrentPeer> peers = torrentPeerMapper.selectPeersByTorrentId(torrentId);
        List<PeerEncoder.PeerInfo> result = new ArrayList<>();
        for (TorrentPeer peer : peers) {
            result.add(new PeerEncoder.PeerInfo(peer.getIp(), peer.getPort()));
        }
        return result;
    }
    /**
     * 处理 tracker 客户端上报数据
     */
    public void handleAnnounce(
            Long userId, Long torrentId, String peerId, String ip, int port,
            String role, Long uploaded, Long downloaded, String event
    ) {
        // Step 1: 插入 tracker_reports 表
        TrackerReport report = new TrackerReport();
        report.setUserId(userId);
        report.setTorrentId(torrentId);
        report.setPeerId(peerId);
        report.setIp(ip);
        report.setUploaded(uploaded);
        report.setDownloaded(downloaded);
        report.setEvent(event);

        trackerReportMapper.insertReport(report);

        // Step 2: 更新或插入 torrent_peers 表
        TorrentPeer existing = torrentPeerMapper.selectByTorrentIdAndPeerId(torrentId, peerId);
        if (existing == null) {
            TorrentPeer peer = new TorrentPeer();
            peer.setUserId(userId);
            peer.setTorrentId(torrentId);
            peer.setPeerId(peerId);
            peer.setIp(ip);
            peer.setPort(port);
            peer.setRole(role);
            peer.setUploaded(uploaded);
            peer.setDownloaded(downloaded);
            torrentPeerMapper.insertPeer(peer);
        } else {
            existing.setIp(ip);
            existing.setPort(port);
            existing.setRole(role);
            existing.setUploaded(uploaded);
            existing.setDownloaded(downloaded);
            torrentPeerMapper.updatePeer(existing);
        }

        // Step 3: 如果是 STOPPED 事件，移除 peer
        if ("STOPPED".equalsIgnoreCase(event)) {
            torrentPeerMapper.deleteByTorrentIdAndPeerId(torrentId, peerId);
        }
    }


    public List<String> getAllInfoHashes() {
        return torrentMapper.getAllInfoHashes();
    }

}

